package com.hcm.kernel.util;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

/**
 * Created by zhangzunwei on 15/5/29.
 */
public class JSONUtil {

    //将null改为“”
    public static String toJSONString(Object object,
                                      SerializerFeature...features) {
        SerializeWriter out = new SerializeWriter();
        String s;
        JSONSerializer serializer = new JSONSerializer(out);
        SerializerFeature arr$[] = features;
        int len$ = arr$.length;
        for (int i$ = 0; i$ < len$; i$++) {
            SerializerFeature feature = arr$[i$];
            serializer.config(feature, true);
        }

        serializer.getValueFilters().add(new ValueFilter() {
            public Object process(Object obj, String s, Object value) {
                if(null!=value) {
                    if(value instanceof java.util.Date) {
                        return String.format("%1$tF %1tT", value);
                    }else if(value instanceof BigDecimal){
                        return new MyBigDecimal(value.toString()).toString();
                    }
                    else
                        return value;
                }else {
                    return null;
                }
            }
        });
        serializer.write(object);
        s = out.toString();
        out.close();
        return s;
    }

    public static String toStr(Object obj){
        if(obj == null){
            return "";
        }
        return obj.toString();
    }

    public static String toJson(String json){
        json = StringUtils.replace(json, "\\", "");
        json = StringUtils.replace(json, "\"[", "[");
        json = StringUtils.replace(json, "]\"", "]");
        json = StringUtils.replace(json, "\"{", "{");
        json = StringUtils.replace(json, "}\"", "}");
        //json = StringUtils.replace(json,"\"","\\\"");
        return json;
    }

}

